package net.wofly.sale.order.service.impl;

import net.wofly.common.pay.service.PayService;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IReceivingAddrService;
import net.wofly.right.service.IUserRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.sale.activity.service.IActivityService;
import net.wofly.sale.commodity.service.IChannelCommodityTmlMappingService;
import net.wofly.sale.commodity.service.ICommodityChannelService;
import net.wofly.sale.commodity.service.ICommodityService;
import net.wofly.sale.commodity.service.ICommodityTmlService;
import net.wofly.sale.commodity.service.IOrderTypeChannelMappingService;
import net.wofly.sale.commodity.service.IRoleDefaultOrderTypeService;
import net.wofly.sale.order.OrderConfig;
import net.wofly.sale.order.flow.IOrderFlowService;
import net.wofly.sale.order.repository.SaleOrderRepository;
import net.wofly.sale.order.service.IIntroducerService;
import net.wofly.sale.order.service.IOrderReceivingAddrService;
import net.wofly.sale.order.service.IOrderTypeService;
import net.wofly.sale.order.service.IPayInfoPicService;
import net.wofly.sale.order.service.IPayInfoService;
import net.wofly.sale.order.service.IRoleOrderTypeService;
import net.wofly.sale.order.service.ITakeGoodsShopInfoService;
import net.wofly.sale.shoppingcart.service.ICartListService;
import net.wofly.sale.stock.service.IStockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;


@Service("iSaleOrderServiceBak")
@Transactional
public class SaleOrderServiceImplBak {
    
    private final String COMMA_SIGN = ",";
    Logger logger = LoggerFactory.getLogger(SaleOrderServiceImplBak.class);
    @Autowired
    IOrderFlowService iOrderFlowService;
    @Autowired
    private OrderConfig orderConfig;
    @Autowired
    private SaleOrderRepository saleOrderRepository;
    @Autowired
    private ICommodityChannelService iCommodityChannelService;
    @Autowired
    private IReceivingAddrService iReceivingAddrService;
    @Autowired
    private ICommodityService iCommodityService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private PayService payService;
    @Autowired
    private IActivityService iActivityService;
    @Autowired
    private ICartListService iCartListService;
    @Autowired
    private IStockService iStockService;
    @Autowired
    private IUserRoleService iUserRoleService;
    @Autowired
    private IIntroducerService iIntroducerService;
    @Autowired
    private IPayInfoService iPayInfoService;
    @Autowired
    private IOrderReceivingAddrService iOrderReceivingAddrService;
    @Autowired
    private ITakeGoodsShopInfoService iTakeGoodsShopInfoService;
    @Autowired
    private IOrganizationService iOrganizationService;
    @Autowired
    private IOrderTypeService iOrderTypeService;
    @Autowired
    private IRoleOrderTypeService iRoleOrderTypeService;
    @Autowired
    private IOrderTypeChannelMappingService iOrderTypeChannelMappingService;
    @Autowired
    private ICommodityTmlService iCommodityTmlService;
    @Autowired
    private IChannelCommodityTmlMappingService iChannelCommodityTmlMappingService;
    
    @Autowired
    private IRoleDefaultOrderTypeService iRoleDefaultOrderTypeService;
    
    @Autowired
    private IPayInfoPicService iPayInfoPicService;
    
//    @Override
//    public Order save(Order entity) {
//        return saleOrderRepository.save(entity);
//    }
//
//    @Override
//    public void delete(Order entity) {
//        saleOrderRepository.delete(entity);
//    }
//
//    @Override
//    public void delete(String key) {
//        saleOrderRepository.delete(key);
//    }
//
//    @Override
//    public Order findOne(String key) {
//        return saleOrderRepository.findOne(key);
//    }
//
//    @Override
//    public Object findMaxOrderNoByDate(String dateStr) {
//        return saleOrderRepository.findMaxOrderNoByDate(dateStr);
//    }
//
//    @Override
//    public List<Order> save(List<Order> entityList) {
//        return (List<Order>) saleOrderRepository.save(entityList);
//    }
//
//    @Override
//    public Page<Order> findAll(Specification specification, Pageable pageable) {
//        return saleOrderRepository.findAll(specification, pageable);
//    }
//
//    @Override
//    public List<Order> findByInProcessInsID(List<String> processInsIDs) {
//        return saleOrderRepository.findByProcessInsIDIn(processInsIDs);
//    }
//
//    @Override
//    public Order findByProcessInsID(String processInsID) {
//        return saleOrderRepository.findByProcessInsID(processInsID);
//    }
//
//    @Override
//    public ReturnBean<Order> createOrder(Order order) throws CloneNotSupportedException {
//        String orderID = Identities.uuid2();
//        Long modifyDate = System.currentTimeMillis();
//        order.setOrderID(orderID);
//
//        // 先校验库存 后 处理礼品
//        // 判断是自助下单，还是代下单
//        User buyer = iUserService.findOne(order.getBuyer());
//        if (buyer == null) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE.intValue(), "下单人buyerID不正确，未找到对应用户");
//        }
//
//        List<Role> roles = iUserRoleService.findRolesByUserID(order.getBuyer());
//        if (CollectionUtils.isEmpty(roles)) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE.intValue(), "下单人buyerID对应的角色不存在，暂时不能下单");
//        }
//
//        //暂时考虑一个用户只有一个角色
//        Role role = roles.get(0);
//
//        //设置orderType
//        if (role.getRoleID().startsWith("1")) {
//            //员工
//            if (OrderType.内欠订单.getValue().intValue() == order.getOrderType()) {
//                //TODO Q: 内欠订单是否是自助下单 ，目前按excel 表格中实现是自助下单， 需要确认
//                order.setPlaceOrderType(PlaceOrderType.自助下单.getValue());
//            } else {
//                if (StringUtils.isEmpty(order.getCustomerUserID())) {
//                    return new ReturnBean<>(ResultCode.ERROR_SERVICE.intValue(), "代下订单，客户ID不能为空");
//                }
//                order.setPlaceOrderType(PlaceOrderType.代客下单.getValue());
//            }
//        } else {
//            order.setPlaceOrderType(PlaceOrderType.自助下单.getValue());
//        }
//
//        //库存不足提示，默认false ，即默认为库存是足够的， 不够时，提示前端
//        if (OrderType.订货会流通订单.getValue().intValue() == order.getOrderType()
//                || OrderType.订货会酒店订单.getValue().intValue() == order.getOrderType()) {
//            //订货会订单不减库存，需要给客户创建虚拟库存，便于以后还货订单时减客户的库存
//            if (CollectionUtils.isNotEmpty(order.getOrderContents())) {
//                // 入库
//                InStock inStock = new InStock();
//                inStock.setInStockType(InStockType.订货会订单.getValue());
//                inStock.setInStocker(order.getBuyer());
//                inStock.setProofID(orderID);
//                inStock.setWarehouseID(order.getCustomerUserID());
//                inStock.setModifyDate(modifyDate);
//                List<InOutStockDetail> inOutStockDetails = new ArrayList<>();
//                for (OrderContent orderContent : order.getOrderContents()) {
//                    buildInOutStockDetail(modifyDate, order, inOutStockDetails, orderContent);
//                }
//                inStock.setInOutStockDetails(inOutStockDetails);
//                iStockService.addInStock(inStock);
//            }
//        } else {
//            //非订货会订单减库存
//            String wareHouseIDs = getWarehouseID(order, buyer, role);
//            if (StringUtils.isEmpty(wareHouseIDs)) {
//                logger.info(">>> 未找到对应的仓库信息，不能下单");
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE.intValue(), "未找到对应的仓库信息，暂时不能下单");
//            }
//            boolean warningFlag = false;
//            StringBuffer infoStr = new StringBuffer();
//            // 出库
//            OutStock outStock = new OutStock();
//            outStock.setOutStockID(Identities.uuid2());
//            outStock.setWarehouseID(wareHouseIDs);
//            outStock.setOutStockType(OutStockType.订单出库.getValue());
//            outStock.setProofID(orderID);
//            outStock.setOutStocker(order.getBuyer());
//            outStock.setModifyDate(modifyDate);
//            List<InOutStockDetail> inOutStockDetails = new ArrayList<>();
//            if (CollectionUtils.isNotEmpty(order.getOrderContents())) {
//                for (OrderContent content : order.getOrderContents()) {
//                    //还货订单是减销售和客户的虚拟库存，其他都是只减一个库存，此处只减第一个，因为还货订单是新加了单独的接口
//                    String wareHouseID = wareHouseIDs.split(COMMA_SIGN)[0];
//
//                    CommodityTerminal commodityTerminal = getCommodityTerminal(String.valueOf(order.getOrderType()),
//                            content.getCommodityChannelID());
//
//                    Stock stock = iStockService.findByWarehouseIDAndCommodityTerminalID(wareHouseID,
//                            commodityTerminal.getCommodityTerminalID());
//                    if (stock != null) {
//                        if (stock.getNum() >= content.getNum()) {
//                            InOutStockDetail inOutStockDetail = new InOutStockDetail();
//                            inOutStockDetail.setInOutStockDetailID(Identities.uuid2());
//                            inOutStockDetail.setCommodityTerminalID(commodityTerminal.getCommodityTerminalID());
//                            inOutStockDetail.setNum(content.getNum());
//                            inOutStockDetail.setModifyDate(modifyDate);
//                            inOutStockDetails.add(inOutStockDetail);
//                        } else if (stock.getNum() < content.getNum()) {
//                            logger.info(
//                                    content.getCommodity() != null ? content.getCommodity().getCommodityName() :
//                                            content.getCommodityChannelID() + "商品库存不足");
//                            //content.setRestStockNum(stock.getNum());
//                            warningFlag = true;
//                        }
//                    } else {
//                        logger.info(content.getCommodity() != null ? content.getCommodity().getCommodityName() : content
//                                .getCommodityChannelID() + "商品库存不足");
//                        warningFlag = true;
//                        //content.setRestStockNum(0);
//                    }
//                }
//            }
//            if (warningFlag && orderConfig.isCheckStock()) {
//                //先注释以下代码，不进行强制校验，需要前段配合 调试后放开
//                String msg = "部分商品库存不足，请重新检查数量下单";
//                if (OrderType.还货订单.getValue().intValue() == order.getOrderType()) {
//                    msg = "业务员的库存中" + msg;
//                }
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE_NOT_ENOUGH.intValue(), msg, order);
//            }
//            iStockService.addOutStock(outStock);
//        }
//
//        //处理订单信息，主要是结合活动计算礼品  礼品是和活动一起的， 有活动才有礼品
//        ReturnBean<Order> res = handleOrder(order, orderID);
//        if (res.getCode() != ResultCode.SUCCESS.intValue()) {
//            return new ReturnBean<>(res.getCode(), res.getMsg());
//        }
//        // 订单的礼品总数量
//        int totalGiftNum = 0;
//        Set<Gift> giftSet = new HashSet<>();
//        // 商品GIFT
//        List<OrderContent> orderContents = res.getResult().getOrderContents();
//        for (OrderContent content : orderContents) {
//            List<ActivityGift> activityGifts = content.getActivityGifts();
//            if (CollectionUtils.isNotEmpty(activityGifts)) {
//                for (ActivityGift activityGift : activityGifts) {
//                    totalGiftNum += activityGift.getNum();
//                    Gift gift = new Gift();
//                    gift.setGiftID(Identities.uuid2());
//                    gift.setModifyDate(System.currentTimeMillis());
//                    gift.setActivityGiftID(activityGift.getActivityGiftID());
//                    gift.setCommodityChannelID(content.getCommodityChannelID());
//                    gift.setNum(activityGift.getNum());
//                    gift.setRelateType(GiftRelateType.订单内商品.getValue());
//                    gift.setRelateID(content.getOrderContentID());
//                    gift.setOrderID(orderID);
//                    gift.setOrderContentID(content.getOrderContentID());
//                    giftSet.add(gift);
//                }
//            }
//            content.setPreorderNum(content.getNum());
//        }
//        //订单GIFT
//        List<ActivityGift> activityGifts = res.getResult().getActivityGifts();
//        if (CollectionUtils.isNotEmpty(activityGifts)) {
//            for (ActivityGift activityGift : activityGifts) {
//                totalGiftNum += activityGift.getNum();
//                Gift gift = new Gift();
//                gift.setGiftID(Identities.uuid2());
//                gift.setActivityGiftID(activityGift.getActivityGiftID());
//                //gift.setCommodityChannelID(content.getCommodityChannelID());
//                gift.setNum(activityGift.getNum());
//                gift.setRelateType(GiftRelateType.订单.getValue());
//                gift.setRelateID(order.getOrderID());
//                gift.setOrderID(orderID);
//                giftSet.add(gift);
//            }
//        }
//
//        order.setGiftNum(totalGiftNum);
//        //  GIFT 表插入数据
//        order.setGifts(giftSet);
//
//        if (order.getPlaceOrderType() == PlaceOrderType.代客下单.getValue().intValue()) {
//            if (OrderType.会员订单.getValue().intValue() == order.getOrderType()
//                    || OrderType.签单订单.getValue().intValue() == order.getOrderType()
//                    || OrderType.宴会订单.getValue().intValue() == order.getOrderType()) {
//                order.setGoodTransportType(GoodTransportType.门店自取.getValue());
//            } else {
//                order.setGoodTransportType(GoodTransportType.送货上门.getValue());
//            }
//        } else {
//            //自助下单必须选门店
//            if (null == order.getTakeGoodsShopInfo()) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "取货门店不能为空");
//            }
//        }
//
//        if (order.getGoodTransportType().intValue() == GoodTransportType.送货上门.getValue()) {
//            //收地地址
//            OrderReceivingAddr orderReceivingAddr = order.getOrderReceivingAddr();
//            if (orderReceivingAddr == null) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "收货地址不能为空");
//            }
//            ReceivingAddr receivingAddr = iReceivingAddrService.findOne(orderReceivingAddr.getReceivingAddrID());
//            if (receivingAddr == null) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "收货地址ID不正确");
//            }
//            orderReceivingAddr.setOrderID(orderID);
//            orderReceivingAddr.setOrderReceivingAddrID(Identities.uuid2());
//            orderReceivingAddr.setModifyDate(modifyDate);
//            orderReceivingAddr.setReceivingAddr(receivingAddr);
//            iOrderReceivingAddrService.save(orderReceivingAddr);
//            order.setOrderReceivingAddr(orderReceivingAddr);
//        } else {
//            TakeGoodsShopInfo takeGoodsShopInfo = order.getTakeGoodsShopInfo();
//            if (null == takeGoodsShopInfo) {
//                takeGoodsShopInfo = new TakeGoodsShopInfo();
//                //代客下单 门店为空时，后台自动设置为销售的所属门店
//                takeGoodsShopInfo.setShopOrgID(buyer.getOrganizationID());
//            }
//            takeGoodsShopInfo.setTakeGoodsShopInfoID(Identities.uuid2());
//            takeGoodsShopInfo.setOrderID(orderID);
//            takeGoodsShopInfo.setModifyDate(System.currentTimeMillis());
//            iTakeGoodsShopInfoService.save(takeGoodsShopInfo);
//
//            Organization organization = iOrganizationService.findOne(takeGoodsShopInfo.getShopOrgID());
//            takeGoodsShopInfo.setOrganization(organization);
//            order.setTakeGoodsShopInfo(takeGoodsShopInfo);
//        }
//
//        if (order.getPlaceOrderType().intValue() == PlaceOrderType.自助下单.getValue()) {
//            order.setCustomerUserID(order.getBuyer());
//        }
//
//        order.setOrderCommitTime(modifyDate);
//
//        // 介绍人
//        Introducer introducer = order.getIntroducer();
//        if (introducer != null) {
//            introducer.setIntroducerID(Identities.uuid2());
//            introducer.setOrderID(orderID);
//            introducer.setModifyDate(System.currentTimeMillis());
//            //iIntroducerService.save(introducer);
//        }
//
//        if (!OrderType.还货订单.getValue().equals(order.getOrderType())
//                && !OrderType.内欠订单.getValue().equals(order.getOrderType())) {
//            //设置订单的付款截止时间
//            order.setPayDeadline(System.currentTimeMillis() + orderConfig.getTimeout() * 60 * 60 * 1000);
//        }
//
//        if (OrderType.还货订单.getValue().intValue() == order.getOrderType()) {
//            order.setStatus(OrderStatus.订单己支付.getValue());
//        } else {
//            order.setStatus(OrderStatus.订单提交_未支付.getValue());
//        }
//
//        //生成订单编号
//        String orderNO = generateOrderNO();
//        order.setOrderNo(orderNO);
//
//        save(order);
//
//        // 删除购物车  直接根据人处理  根据人删除 , 购物车是当前登录人的购物车
//        iCartListService.deleteByShoppingCartIDAndShoppingCartType(order.getBuyer(), ShoppingCartType.购物车.getValue());
//
//        // 内欠和还货订单是创建订单时直接启动工作流
//        Integer targetStatus;
//        if (OrderType.内欠订单.getValue().intValue() == order.getOrderType()) {
//            //内欠订单，订单提交_未支付 --> 老板审核
//            iOrderFlowService.startWorkflow(order.getBuyer(), orderID, OrderStatus.订单提交_未支付.getValue().toString(),
//                    null);
//        } else if (OrderType.还货订单.getValue().intValue() == order.getOrderType()) {
//            // 还货订单，订单己支付 --> 出纳平账
//            iOrderFlowService.startWorkflow(order.getBuyer(), orderID, OrderStatus.订单己支付.getValue().toString(), null);
//        }
//
//        if (null != order.getPayDeadline()) {
//            //设置订单的剩余支付时间
//            order.setPayRestTime(order.getPayDeadline() - System.currentTimeMillis());
//        }
//
//        return new ReturnBean<>(ResultCode.SUCCESS, "订单创建成功", order);
//    }
//
//    private String generateOrderNO() {
//        String orderNum = null;
//        String dateStr = LocalDate.now().toString("yyyyMMdd");
//        Object maxOrderNoByDate = findMaxOrderNoByDate(dateStr);
//        if (!StringUtils.isEmpty(maxOrderNoByDate)) {
//            Long orderNo = Long.valueOf(dateStr + maxOrderNoByDate.toString()) + 1;
//            orderNum = String.valueOf(orderNo);
//        } else {
//            orderNum = dateStr + "0001";
//        }
//        return orderNum;
//    }
//
//    @Override
//    public CommodityTerminal getCommodityTerminal(String orderType, String commodityChannelID) {
//        CommodityTerminal commodityTerminal = new CommodityTerminal();
//        CommodityChannel commodityChannel = iCommodityChannelService.findOne(commodityChannelID);
//
//        //根据订单类型找到channel
//        OrderTypeChannelMapping orderTypeChannelMapping = iOrderTypeChannelMappingService.findByOrderType(orderType);
//        if (null == orderTypeChannelMapping) {
//            logger.info(">>> 未找到订单类型和渠道的关系配置数据...");
//            return commodityTerminal;
//        }
//        ChannelCommodityTerminalMapping channelCommodityTerminalMapping = iChannelCommodityTmlMappingService
//                .findByChannel(orderTypeChannelMapping.getChannel());
//        if (null == channelCommodityTerminalMapping) {
//            logger.info(">>> 未找到渠道和商品终端类型的关系配置数据...");
//            return commodityTerminal;
//        }
//        commodityTerminal = iCommodityTmlService.findByCommodityIDAndCommodityTerminalTypeAndStatus(
//                commodityChannel.getCommodityID(), channelCommodityTerminalMapping.getCommodityTerminalType(),
//                CommonStatus.有效.getValue());
//        if (null == commodityTerminal) {
//            logger.info(">>> 未找到商品终端的数据...");
//            return commodityTerminal;
//        }
//        return commodityTerminal;
//    }
//
//    /*//@Override
//    private CommodityTerminal getCommodityChannelByTerminal(String orderType, String commodityTmlID) {
//        //CommodityTerminal commodityTerminal = new CommodityTerminal();
//        CommodityChannel commodityChannel = iCommodityChannelService.findOne(commodityChannelID);
//
//        //根据订单类型找到channel
//        OrderTypeChannelMapping orderTypeChannelMapping = iOrderTypeChannelMappingService.findByOrderType(orderType);
//        if (null == orderTypeChannelMapping) {
//            logger.info(">>> 未找到订单类型和渠道的关系配置数据...");
//            return commodityTerminal;
//        }
//        ChannelCommodityTerminalMapping channelCommodityTerminalMapping = iChannelCommodityTmlMappingService
//                .findByChannel(orderTypeChannelMapping.getChannel());
//        if (null == channelCommodityTerminalMapping) {
//            logger.info(">>> 未找到渠道和商品终端类型的关系配置数据...");
//            return commodityTerminal;
//        }
//        commodityTerminal = iCommodityTmlService.findByCommodityIDAndCommodityTerminalTypeAndStatus(
//                commodityChannel.getCommodityID(), channelCommodityTerminalMapping.getCommodityTerminalType(),
//                CommonStatus.有效.getValue());
//        if (null == commodityTerminal) {
//            logger.info(">>> 未找到商品终端的数据...");
//            return commodityTerminal;
//        }
//        return commodityTerminal;
//    }*/
//
//    /**
//     * 根据订单及用户角色获得仓库信息，用于减库存或者恢复库存操作
//     *
//     * @param order 订单
//     * @param buyer 下单人（操作人）
//     * @param role  下单人的角色
//     * @return
//     */
//    private String getWarehouseIDOld(Order order, User buyer, Role role) {
//        //            100	内部员工	1	0	1506438068780	0	0
//        //            101	老板	1	0	1506438069926	0	0
//        //            102	会计	1	0	1506438756066	0	0
//        //            103	出纳	1	0	1506438882064	0	0
//        //            104	库管	1	0	1506438087268	1	1
//        //            105	店员	1	0	1506438069922	1	2
//        //            106	业务员	1	1	1506438069922	1	3
//        //            107	团购专员	1	0	1506438069922	1	3
//        //            200	客户	1	0	1506438069926	0	0
//        //            201	会员	1	0	1506438045915	0	0
//        //            202	团购	1	0	1506438069926	0	0
//        //            203	流通客户	1	0	1506438069926	0	0
//        //            204	酒店客户	1	0	1506438667946	0	0
//        //            205	签单	1	0	1506438044981	0	0
//        String wareHouseID = null;
//        if (order.getPlaceOrderType().intValue() == PlaceOrderType.自助下单.getValue()) {
//            if (RoleEnum.会员.getValue().equals(role.getRoleID())) {
//                // 会员 减店面库存，根据客户选择的发货（提货）门店确定 订单告知是哪个店面 , 才可以 ;
//                TakeGoodsShopInfo takeGoodsShopInfo = order.getTakeGoodsShopInfo();
//                if (null == takeGoodsShopInfo) {
//                    //创建订单时不为空，查询时是为空的，主动去查
//                    takeGoodsShopInfo = iTakeGoodsShopInfoService.findByOrderID(order.getOrderID());
//                }
//                //门店ID
//                wareHouseID = takeGoodsShopInfo.getShopOrgID();
//            } else if (RoleEnum.店员.getValue().equals(role.getRoleID())) {
//                // 另外内欠订单是店员下单，减的是店面的库存
//                wareHouseID = buyer.getOrganizationID();
//            } else if (RoleEnum.流通客户.getValue().equals(role.getRoleID()) || RoleEnum.酒店客户.getValue().equals(
//                    role.getRoleID())) {
//                // 流通客户和酒店客户 ,减对应销售员库存
//                wareHouseID = buyer.getFollowUserID();
//            }
//            order.setCustomerUserID(order.getBuyer());
//        } else if (order.getPlaceOrderType().intValue() == PlaceOrderType.代客下单.getValue()) {
//            if (RoleEnum.店员.getValue().equals(role.getRoleID())) {
//                // 店员（内欠订单）和 签单  , 减店面库存
//                wareHouseID = buyer.getOrganizationID();
//            } else if (RoleEnum.业务员.getValue().equals(role.getRoleID()) || RoleEnum.团购专员.getValue().equals(
//                    role.getRoleID())) {
//                // 业务员（销售）和团购 ,减对应销售员库存
//                wareHouseID = buyer.getUserID();
//                if (OrderType.还货订单.getValue().intValue() == order.getOrderType()) {
//                    //还货订单， 要减客户的虚拟库存和销售的库存
//                    wareHouseID = order.getCustomerUserID() + COMMA_SIGN + buyer.getUserID();
//                }
//            }
//        }
//        return wareHouseID;
//    }
//
//    /**
//     * 根据订单及用户角色获得仓库信息，用于减库存或者恢复库存操作
//     *
//     * @param order 订单
//     * @param buyer 下单人（操作人）
//     * @param role  下单人的角色
//     * @return
//     */
//    private String getWarehouseID(Order order, User buyer, Role role) {
//        //            100	内部员工	1	0	1506438068780	0	0
//        //            101	老板	1	0	1506438069926	0	0
//        //            102	会计	1	0	1506438756066	0	0
//        //            103	出纳	1	0	1506438882064	0	0
//        //            104	库管	1	0	1506438087268	1	1
//        //            105	店员	1	0	1506438069922	1	2
//        //            106	业务员	1	1	1506438069922	1	3
//        //            107	团购专员	1	0	1506438069922	1	3
//        //            200	客户	1	0	1506438069926	0	0
//        //            201	会员	1	0	1506438045915	0	0
//        //            202	团购	1	0	1506438069926	0	0
//        //            203	流通客户	1	0	1506438069926	0	0
//        //            204	酒店客户	1	0	1506438667946	0	0
//        //            205	签单	1	0	1506438044981	0	0
//        String wareHouseID = null;
//        if (role.getRoleID().startsWith("1")) {
//            //内部员工，库存直接从user表中查到，取user表中的wareHouseID即可，因为是否有仓库及仓库的ID都是在用户管理的进行维护的
//            wareHouseID = buyer.getWarehouseID();
//            if (OrderType.还货订单.getValue().intValue() == order.getOrderType()) {
//                //还货订单， 要减客户的虚拟库存和销售的库存，
//                wareHouseID = wareHouseID + COMMA_SIGN + order.getCustomerUserID();
//            }
//        } else {
//            if (RoleEnum.会员.getValue().equals(role.getRoleID())) {
//                // 会员 减店面库存，根据客户选择的发货（提货）门店确定 订单告知是哪个店面 , 才可以 ;
//                TakeGoodsShopInfo takeGoodsShopInfo = order.getTakeGoodsShopInfo();
//                if (null == takeGoodsShopInfo) {
//                    //创建订单时不为空，查询时是为空的，主动去查
//                    takeGoodsShopInfo = iTakeGoodsShopInfoService.findByOrderID(order.getOrderID());
//                }
//                //门店ID
//                wareHouseID = takeGoodsShopInfo.getShopOrgID();
//            } else if (RoleEnum.流通客户.getValue().equals(role.getRoleID()) || RoleEnum.酒店客户.getValue().equals(
//                    role.getRoleID())) {
//                // 流通客户和酒店客户 ,减对应销售员库存
//                if (StringUtils.isEmpty(buyer.getFollowUserID())) {
//                    logger.info(">>> 流通客户||酒店客户 自助下单，但是未找到对应的销售员信息 ");
//                } else {
//                    User saler = iUserService.findOne(buyer.getFollowUserID());
//                    if (saler == null) {
//                        logger.info(">>> 流通客户||酒店客户 自助下单，对应的销售员信息（user表中）不存在 ");
//                    } else {
//                        wareHouseID = saler.getWarehouseID();
//                    }
//                }
//            }
//            order.setCustomerUserID(order.getBuyer());
//        }
//        return wareHouseID;
//    }
//
//    @Override
//    public ReturnBean<Order> handleOrder(Order order) throws CloneNotSupportedException {
//        return handleOrder(order, "");
//    }
//
//    private ReturnBean<Order> handleOrder(Order order, String orderID) throws CloneNotSupportedException {
//        Long modifyDate = System.currentTimeMillis();
//        int totalNum = 0;
//        // 总价
//        Integer totalAmount = 0;
//        //活动总价
//        Integer totalActivityAmount = 0;
//        Integer totalGiftNum = 0;
//
//        // 判断订单类型不能为空
//        if (order.getOrderType() == null || !OrderType.isValueCorrect(order.getOrderType())) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "订单类型不能为空或者订单类型不正确");
//        }
//
//        //订单内容 、 商品活动、 订单活动
//
//        //计算订单礼品要考虑4个维度 ①商品类型 ②活动类型 ③订单类型  ④数量（num 或者 amount）
//        List<OrderContent> orderContents = order.getOrderContents();
//        for (OrderContent orderContent : orderContents) {
//            CommodityChannel commodityChannel = iCommodityChannelService.findOne(orderContent.getCommodityChannelID());
//            if (null == commodityChannel) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "订单内容的商品渠道ID不正确");
//            }
//
//            List<ActivityGift> activityGifts = new ArrayList<>();
//
//            // 此处考虑活动价格   //查询有效的活动信息
//            List<Activity> activityList = iActivityService
//                    .findByCommodityChannelIDAndStatusAndStartTimeBeforeAndEndTimeAfter(
//                            orderContent.getCommodityChannelID(), ActivityStatus.发布.getValue(), modifyDate, modifyDate);
//
//            if (CollectionUtils.isNotEmpty(activityList)) {
//                for (Activity activity : activityList) {
//                    Integer orderType = activity.getOrderType();
//                    if (orderType.intValue() == -1) {
//                        // 适用于所有订单
//                        getChannelActivityGifts(orderContent, commodityChannel, activityGifts, activity);
//                    } else {// 指定类型的订单
//                        if (orderType.intValue() == order.getOrderType()) {
//                            getChannelActivityGifts(orderContent, commodityChannel, activityGifts, activity);
//                        }
//                    }
//                }
//            }
//
//            totalAmount += commodityChannel.getCommodityChannelPrise() * orderContent.getNum();
//            totalNum += orderContent.getNum();
//
//            orderContent.setPrice(commodityChannel.getCommodityChannelPrise());
//            orderContent.setTotalPrice(commodityChannel.getCommodityChannelPrise() * orderContent.getNum());
//
//            orderContent.setOrderID(orderID);
//            orderContent.setModifyDate(modifyDate);
//            orderContent.setOrderContentID(Identities.uuid2());
//        }
//
//        //设置订单的相关信息
//        //购买商品的数量
//        order.setCommodityNum(totalNum);
//        // 商品总价
//        order.setAmount(totalAmount);
//        //活动商品总价  暂时=商品总价 ，因为活动 只有赠品，没有打折了 实际应该应是totalActivityAmount, 打折之后的价格
//        totalActivityAmount = totalAmount;
//        order.setActivityAmount(totalActivityAmount);
//        // 订单优惠价 等于商品总价-活动总价
//        order.setOrderDiscounts(order.getAmount() - order.getActivityAmount());
//        // 实收 活动价-支付优惠
//        order.setRealPrice(order.getActivityAmount() - order.getPayDiscounts());
//
//        if (OrderType.内欠订单.getValue().intValue() == order.getOrderType()
//                || OrderType.还货订单.getValue().intValue() == order.getOrderType()) {
//            order.setRealPrice(0);
//        }
//
//        // 订单的活动信息
//        getOrderActivityGifts(order, modifyDate);
//
//        return new ReturnBean<>(ResultCode.SUCCESS, "success", order);
//    }
//
//    private void getOrderActivityGifts(Order order, long modifyDate) {
//        List<ActivityGift> orderActivityGiftList = new ArrayList<>();
//        //   订单的活动 两种方式 , 查询订单的活动时，要加上活动的状态、起止时间进程查询
//        List<Activity> activities = iActivityService.findByActivityTypeAndStatusAndStartTimeBeforeAndEndTimeAfter(
//                ActivityType.单一订单中商品数量.getValue(), ActivityStatus.发布.getValue(), modifyDate, modifyDate);
//        if (CollectionUtils.isNotEmpty(activities)) {
//            for (Activity activity : activities) {
//                if (activity.getOrderType().intValue() == -1) {
//                    if (order.getCommodityNum() >= activity.getNum()) {
//                        orderActivityGiftList.addAll(activity.getActivityGifts());
//                    }
//                } else {
//                    if (activity.getOrderType().intValue() == order.getOrderType() && order.getCommodityNum() >=
//                            activity.getNum()) {
//                        orderActivityGiftList.addAll(activity.getActivityGifts());
//                    }
//                }
//            }
//        }
//
//        activities = iActivityService.findByActivityTypeAndStatusAndStartTimeBeforeAndEndTimeAfter(
//                ActivityType.单一订单中商品总价.getValue(), ActivityStatus.发布.getValue(), modifyDate, modifyDate);
//        if (CollectionUtils.isNotEmpty(activities)) {
//            for (Activity activity : activities) {
//                if (activity.getOrderType().intValue() == -1) {
//                    if (order.getRealPrice() >= activity.getAmount()) {
//                        orderActivityGiftList.addAll(activity.getActivityGifts());
//                    }
//                } else {
//                    if (activity.getOrderType().intValue() == order.getOrderType() && order.getRealPrice() >=
//                            activity.getAmount()) {
//                        orderActivityGiftList.addAll(activity.getActivityGifts());
//                    }
//                }
//            }
//        }
//        buildGiftsCommodityInfo(orderActivityGiftList);
//        order.setActivityGifts(orderActivityGiftList);
//    }
//
//    private void getChannelActivityGifts(
//            OrderContent orderContent, CommodityChannel commodityChannel, List<ActivityGift> activityGifts,
//            Activity activity) throws CloneNotSupportedException {
//        if (activity.getActivityType().intValue() == ActivityType.单一商品数量.getValue() && orderContent.getNum() >=
//                activity.getNum()) {
//            activityGifts.addAll(activity.getActivityGifts());
//        } else if (activity.getActivityType().intValue() == ActivityType.单一商品总价.getValue() &&
//                (orderContent.getNum() * commodityChannel.getCommodityChannelPrise()) >= activity.getAmount()) {
//            activityGifts.addAll(activity.getActivityGifts());
//        } else if (activity.getActivityType().intValue() == ActivityType.单一商品数量累计_每满赠.getValue()) {
//            int giftTimes = new BigDecimal(
//                    Math.floor(orderContent.getNum() / activity.getNum())).intValue();
//            List<ActivityGift> gifts = activity.getActivityGifts();
//            if (CollectionUtils.isNotEmpty(gifts)) {
//                for (ActivityGift gift : gifts) {
//                    ActivityGift realGift = gift.clone();
//                    realGift.setNum(giftTimes * gift.getNum());
//                    activityGifts.add(realGift);
//                }
//            }
//        } else if (activity.getActivityType().intValue() == ActivityType.单一商品总价.getValue()) {
//            int giftTimes = new BigDecimal(
//                    Math.floor((orderContent.getNum() * commodityChannel.getCommodityChannelPrise()) / activity
//                            .getAmount())).intValue();
//            List<ActivityGift> gifts = activity.getActivityGifts();
//            if (CollectionUtils.isNotEmpty(gifts)) {
//                for (ActivityGift gift : gifts) {
//                    ActivityGift realGift = gift.clone();
//                    realGift.setNum(giftTimes * gift.getNum());
//                    activityGifts.add(realGift);
//                }
//            }
//        }
//        buildGiftsCommodityInfo(activityGifts);
//        orderContent.setActivityGifts(activityGifts);
//    }
//
//    private void buildGiftsCommodityInfo(List<ActivityGift> activityGifts) {
//        if (CollectionUtils.isNotEmpty(activityGifts)) {
//            for (ActivityGift activityGift : activityGifts) {
//                CommodityChannel channel = iCommodityChannelService.findOne(activityGift.getCommodityChannelID());
//                Commodity commodity = iCommodityService.findOne(channel.getCommodityID());
//                activityGift.setCommodity(commodity);
//            }
//        }
//    }
//
//    /**
//     * 获取客户订单，包括客户自己下单及销售代为下单的所有订单
//     * <ul>
//     * <li> </li>
//     * </ul>
//     *
//     * @param customerUserID
//     */
//    @Override
//    public ReturnBean<PageWrapper<Order>> getCustomerOrder(String customerUserID, Integer pageNum, Integer pageSize) {
//        Condition condition = new Condition();
//        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
//        filterConditions.add(new FilterCondition(customerUserID, "customerUserID", ConditionRelate.and.name(),
//                Operation.eq.name(), 1));
//        condition.setFilterCondition(filterConditions);
//
//        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), Order.class).getResult();
//
//        Pageable pageable = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.DESC, "orderCommitTime"));
//        Page<Order> page = findAll(condition.getSpecification(), pageable);
//        List<Order> orderList = page.getContent();
//        if (CollectionUtils.isNotEmpty(orderList)) {
//            for (Order order : orderList) {
//                getOrderInfo(order);
//            }
//        }
//        return new ReturnBean<PageWrapper<Order>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
//    }
//
//    private void buildCommodityInfo(Order order) {
//        List<OrderContent> contentList = order.getOrderContents();
//        if (CollectionUtils.isNotEmpty(contentList)) {
//            for (OrderContent orderContent : contentList) {
//                String commodityChannelID = orderContent.getCommodityChannelID();
//                CommodityChannel commodityChannel = iCommodityChannelService.findOne(commodityChannelID);
//                if (commodityChannel != null) {
//                    ReturnBean<Commodity> commodityReturnBean = iCommodityService.getCommodityChannelByID(
//                            commodityChannel.getCommodityID());
//                    if (commodityReturnBean.getCode() == 0) {
//                        orderContent.setCommodity(commodityReturnBean.getResult());
//                    }
//                } else {
//                    logger.info("商品渠道ID为空，不能查询到对应的商品详情");
//                }
//            }
//        }
//    }
//
//    @Override
//    public ReturnBean<Order> getOrder(String orderID) {
//        Order order = findOne(orderID);
//        if (order == null) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "订单ID不正确");
//        }
//
//        return new ReturnBean<Order>(ResultCode.SUCCESS, "查询成功", getOrderInfo(order));
//    }
//
//    private Order getOrderInfo(Order order) {
//
//        translateOrderInfo(order);
//
//        buildCommodityInfo(order);
//
//        OrderReceivingAddr orderReceivingAddr = iOrderReceivingAddrService.findByOrderID(order.getOrderID());
//        order.setOrderReceivingAddr(orderReceivingAddr);
//
//        Integer goodTransportType = order.getGoodTransportType();
//        if (GoodTransportType.送货上门.getValue().intValue() == goodTransportType) {
//            ReceivingAddr addr = iReceivingAddrService.findOne(orderReceivingAddr.getReceivingAddrID());
//            order.setAddrStr(null != addr ? addr.getReceivingAddr() : "");
//        } else {
//            TakeGoodsShopInfo takeGoodsShopInfo = iTakeGoodsShopInfoService.findByOrderID(order.getOrderID());
//            Organization organization = iOrganizationService.findOne(takeGoodsShopInfo.getShopOrgID());
//            order.setAddrStr(null != organization ? organization.getAddr() : "");
//        }
//
//        PayInfo payInfo = iPayInfoService.findByOrderIDOrderByPayTimeDesc(order.getOrderID());
//        order.setPayInfo(payInfo);
//
//        List<PayInfoPic> payInfoPics = iPayInfoPicService.findByOrderID(order.getOrderID());
//        order.setPayInfoPics(payInfoPics);
//        return order;
//    }
//
//    /**
//     * 对order的数据字典进行转换
//     *
//     * @param order
//     */
//    private void translateOrderInfo(Order order) {
//        order.setStatusStr(OrderStatus.getName(order.getStatus()));
//        order.setOrderTypeStr(OrderType.getName(order.getOrderType()));
//        //客户姓名
//        if (!StringUtils.isEmpty(order.getCustomerUserID())) {
//            User customer = iUserService.findOne(order.getCustomerUserID());
//            order.setCustomerUserName(null != customer ? customer.getName() : "");
//        }
//        // 下单人
//        if (!StringUtils.isEmpty(order.getBuyer())) {
//            User buyer = iUserService.findOne(order.getBuyer());
//            order.setBuyerName(null != buyer ? buyer.getName() : "");
//        }
//        if (null != order.getStatus()) {
//            order.setStatusStr(OrderStatus.getName(order.getStatus()));
//        }
//    }
//
//    @Override
//    public ReturnBean<PageWrapper<Order>> getSalerOrder(
//            String salerID, String orderNo, Integer orderType, String customerName, Integer status, Integer pageNum,
//            Integer pageSize) {
//        if (iUserService.findOne(salerID) == null) {
//            return new ReturnBean<PageWrapper<Order>>(ResultCode.ERROR_SERVICE, "销售员ID不正确");
//        }
//
//        //判断customerID 是否是该销售员的客户
//        //查询销售员的客户信息
//        List<String> customerIDS = new ArrayList<String>();
//        if (org.apache.commons.lang3.StringUtils.isNotEmpty(customerName)) {
//            //  Q:需要确认是否只查询有效客户   A:查询所有客户，产生订单了都算
//            List<User> customerList = iUserService.findByFollowUserIDAndNameLike(salerID, "%" + customerName + "%");
//            if (CollectionUtils.isEmpty(customerList)) {
//                Page page = new PageImpl(new ArrayList());
//                return new ReturnBean<PageWrapper<Order>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
//            } else {
//                for (User user : customerList) {
//                    customerIDS.add(user.getUserID());
//                }
//            }
//        } else {
//            //  Q:需要确认是否只查询有效客户   A:查询所有客户，产生订单了都算
//            List<User> customerList = iUserService.findByFollowUserID(salerID);
//            if (CollectionUtils.isNotEmpty(customerList)) {
//                for (User customer : customerList) {
//                    customerIDS.add(customer.getUserID());
//                }
//            }
//        }
//
//        Condition condition = new Condition();
//        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
//        if (CollectionUtils.isNotEmpty(customerIDS)) {
//            filterConditions.add(new FilterCondition(customerIDS, "customerUserID", ConditionRelate.and.name(),
//                    Operation.in.name(), 1));
//        }
//        if (!StringUtils.isEmpty(orderNo)) {
//            filterConditions.add(
//                    new FilterCondition(orderNo, "orderNo", ConditionRelate.and.name(), Operation.like.name(), 2));
//        }
//        if (orderType != null) {
//            filterConditions.add(new FilterCondition(String.valueOf(orderType), "orderType", ConditionRelate.and.name(),
//                    Operation.eq.name(), 2));
//        }
//        if (status != null) {
//            if (status.intValue() == 9) {
//                filterConditions.add(new FilterCondition("1109", "status",
//                        ConditionRelate.or.name(), Operation.eq.name(), 20, 1, ConditionRelate.and.name()));
//                filterConditions.add(new FilterCondition("1409", "status",
//                        ConditionRelate.or.name(), Operation.eq.name(), 20, 1, ConditionRelate.and.name()));
//                filterConditions.add(new FilterCondition("1509", "status",
//                        ConditionRelate.or.name(), Operation.eq.name(), 20, 1, ConditionRelate.and.name()));
//            } else {
//                filterConditions.add(new FilterCondition(String.valueOf(status), "status", ConditionRelate.and.name(),
//                        Operation.eq.name(), 3));
//            }
//        }
//        filterConditions.add(new FilterCondition(salerID, "buyer", ConditionRelate.or.name(),
//                Operation.eq.name(), 1));
//        condition.setFilterCondition(filterConditions);
//
//        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), Order.class).getResult();
//
//        Pageable pageable = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.DESC, "orderCommitTime"));
//        Page<Order> page = findAll(condition.getSpecification(), pageable);
//        List<Order> orderList = page.getContent();
//        if (CollectionUtils.isNotEmpty(orderList)) {
//            for (Order order : orderList) {
//                getOrderInfo(order);
//            }
//        }
//
//        return new ReturnBean<PageWrapper<Order>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
//    }
//
//    @Override
//    public ReturnBean<PageWrapper<Order>> getOrderByCnd(
//            String orderNo, Integer orderType, String customerName, Integer status, Integer pageNum, Integer pageSize) {
//        Condition condition = new Condition();
//        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
//        if (!StringUtils.isEmpty(customerName)) {
//            if (customerName.length() == 32 && !GeneralHelper.isChinese(customerName)) {
//                filterConditions.add(new FilterCondition(customerName, "customerUserID", ConditionRelate.and.name(),
//                        Operation.eq.name(), 1));
//            } else {
//                List<User> users = null;
//                if (GeneralHelper.isChinese(customerName)) {
//                    users = iUserService.findByNameLike("%" + customerName + "%");
//                } else {
//                    users = iUserService.findByNamePinYinLike(customerName + "%");
//                }
//                if (CollectionUtils.isEmpty(users)) {
//                    Page page = new PageImpl(new ArrayList());
//                    return new ReturnBean<PageWrapper<Order>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
//                }
//                List<String> customerIDs = new ArrayList<>();
//                for (User user : users) {
//                    customerIDs.add(user.getUserID());
//                }
//                filterConditions.add(new FilterCondition(customerIDs, "customerUserID", ConditionRelate.and.name(),
//                        Operation.in.name(), 1));
//            }
//        }
//        if (!StringUtils.isEmpty(orderNo)) {
//            filterConditions.add(
//                    new FilterCondition(orderNo, "orderNo", ConditionRelate.and.name(), Operation.like.name(), 2));
//        }
//        if (orderType != null) {
//            filterConditions.add(new FilterCondition(String.valueOf(orderType), "orderType", ConditionRelate.and.name(),
//                    Operation.eq.name(), 2));
//        }
//        if (status != null) {
//            if (status.intValue() == 9) {
//                filterConditions.add(new FilterCondition("1109", "status",
//                        ConditionRelate.or.name(), Operation.eq.name(), 20, 1, ConditionRelate.and.name()));
//                filterConditions.add(new FilterCondition("1409", "status",
//                        ConditionRelate.or.name(), Operation.eq.name(), 20, 1, ConditionRelate.and.name()));
//                filterConditions.add(new FilterCondition("1509", "status",
//                        ConditionRelate.or.name(), Operation.eq.name(), 20, 1, ConditionRelate.and.name()));
//            } else {
//                filterConditions.add(new FilterCondition(String.valueOf(status), "status", ConditionRelate.and.name(),
//                        Operation.eq.name(), 3));
//            }
//        }
//
//        condition.setFilterCondition(filterConditions);
//
//        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), Order.class).getResult();
//
//        Pageable pageable = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.DESC, "orderCommitTime"));
//        Page<Order> page = findAll(condition.getSpecification(), pageable);
////        List<Order> orderList = page.getContent();
////        if (CollectionUtils.isNotEmpty(orderList)) {
////            for (Order order : orderList) {
////                buildCommodityInfo(order);
////            }
////        }
//
//        List<Order> orderList = page.getContent();
//        if (CollectionUtils.isNotEmpty(orderList)) {
//            for (Order order : orderList) {
//                getOrderInfo(order);
//            }
//        }
//
//        return new ReturnBean<PageWrapper<Order>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
//    }
//
//    @Override
//    public ReturnBean<Order> getOrder(String orderID, Integer payType) {
//        return null;
//    }
//
//    @Override
//    public ReturnBean<String> pay(
//            String orderID, Integer payType, Integer clientType,
//            BigDecimal amount) throws IOException, AlipayApiException {
//        ReturnBean<String> returnBean;
//        Order order = findOne(orderID);
//        if (order == null) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "订单ID不正确");
//        }
//        //  订单金额
//        BigDecimal sum = new BigDecimal(order.getRealPrice()).divide(BigDecimal.valueOf(100));
//
//        if (PayType.支付宝.getValue().intValue() == payType || PayType.微信支付.getValue().intValue() == payType) {
//            payService.doPay(orderID, payType, clientType, String.valueOf(sum));
//        } else {
//            //生成支付信息
//            PayInfo payInfo = new PayInfo();
//            payInfo.setPayInfoID(Identities.uuid2());
//            payInfo.setOrderID(orderID);
//            //默认设置为订单的应付款金额，后续不同的支付方式，再根据前端传入的参数进行设置
//            payInfo.setAmount(order.getRealPrice());
//            payInfo.setPayAccount(null);
//            payInfo.setPayTime(System.currentTimeMillis());
//            payInfo.setPayType(payType);
//
//            //启动工作流， 根据不同的订单类型
//            //Integer targetStatus = OrderUtil.getOnlinePayCurrStatus4Workflow(order, true);
//            Integer currStatus = null;
//            if (PayType.现金.getValue().intValue() == payType) {
//                currStatus = OrderStatus.订单己支付.getValue();
//            } else if (PayType.货到付款.getValue().intValue() == payType) {
//                currStatus = OrderStatus.货到付款_未支付.getValue();
//            } else if (PayType.白条支付.getValue().intValue() == payType) {
//                currStatus = OrderStatus.白条已支付.getValue();
//                payInfo.setAmount(0);
//            } else if (PayType.支付定金.getValue().intValue() == payType) {
//                currStatus = OrderStatus.支付定金.getValue();
//                payInfo.setAmount(amount.multiply(new BigDecimal("100")).intValue());
//            }
//            order.setStatus(currStatus);
//
//            order.setPayTime(System.currentTimeMillis());
//            save(order);
//            // 货到付款的方式也会向PayInfo 表写记录， 单独再提供一个接口给工作流调用，再插入真正的付款信息，付款方式为现金支付
//            iPayInfoService.save(payInfo);
//
//            /*if (PayType.现金.getValue().intValue() == payType || PayType.货到付款.getValue().intValue() == payType
//                    || PayType.白条支付.getValue().intValue() == payType || PayType.支付定金.getValue().intValue() == payType) {
//                iOrderFlowService.startWorkflow(order.getBuyer(), orderID, currStatus.toString(), null);
//            }*/
//
//            //启动工作流， 根据不同的订单类型
//            if (OrderType.会员订单.getValue().intValue() == order.getOrderType().intValue()
//                    && (PayType.现金.getValue().intValue() == payType || PayType.货到付款.getValue().intValue() == payType)) {
//                //销售	客户	现金支付（包括扫码及现金）
//                iOrderFlowService.startWorkflow(order.getBuyer(), orderID, currStatus.toString(), null);
//            } else if ((OrderType.流通订单.getValue().intValue() == order.getOrderType().intValue()
//                    || OrderType.酒店订单.getValue().intValue() == order.getOrderType().intValue())
//                    && (PayType.现金.getValue().intValue() == payType || PayType.货到付款.getValue().intValue() == payType
//                    || PayType.白条支付.getValue().intValue() == payType)) {
//                iOrderFlowService.startWorkflow(order.getBuyer(), orderID, currStatus.toString(), null);
//            } else if (OrderType.签单订单.getValue().intValue() == order.getOrderType().intValue()
//                    && PayType.白条支付.getValue().intValue() == payType) {
//                iOrderFlowService.startWorkflow(order.getBuyer(), orderID, currStatus.toString(), null);
//            } else if (OrderType.订货会酒店订单.getValue().intValue() == order.getOrderType().intValue()
//                    || OrderType.订货会流通订单.getValue().intValue() == order.getOrderType().intValue()
//                    || OrderType.酒店订单.getValue().intValue() == order.getOrderType().intValue()
//                    || OrderType.还货订单.getValue().intValue() == order.getOrderType().intValue()) {
//                iOrderFlowService.startWorkflow(order.getBuyer(), orderID, currStatus.toString(), null);
//            } else if (OrderType.内欠订单.getValue().intValue() == order.getOrderType().intValue()) {
//                iOrderFlowService.startWorkflow(order.getBuyer(), orderID, order.getStatus() + "", null);
//            }
//        }
//
//        return new ReturnBean<>(0, "支付完成");
//    }
//
//    @Override
//    public ReturnBean<Order> getVerifyOrder(String userID, String order) throws CloneNotSupportedException {
//        Order orderEntity = JSON.parseObject(order, Order.class);
//        if (orderEntity == null) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "订单信息不能为空！");
//        }
//
//        return handleOrder(orderEntity);
//    }
//
//    @Override
//    public void orderTimeoutRefresh() {
//        //查询即将过期的订单信息， 不查询还货订单和内欠订单（创建订单时，换货订单和内欠订单没有写支付到期时间的值）
//        //只查询自助下单的、到期未支付的、非内欠订单（内欠订单是店员下单，默认为自助下单）
//        List<Order> orderList = findByPlaceOrderTypeAndStatusAndOrderTypeNotAndPayDeadlineLessThan(
//                PlaceOrderType.自助下单.getValue(), OrderStatus.订单提交_未支付.getValue(), OrderType.内欠订单.getValue(),
//                System.currentTimeMillis());
//
//        //将订单设置为为无效，同时恢复库存
//        if (CollectionUtils.isEmpty(orderList)) {
//            logger.info(">>> 没有找到需要刷新的未支付订单...");
//            return;
//        }
//
//        Long modifyDate = System.currentTimeMillis();
//
//        for (Order order : orderList) {
//            //购买人
//            User buyer = iUserService.findOne(order.getBuyer());
//            //购买人角色
//            List<Role> roles = iUserRoleService.findRolesByUserID(order.getBuyer());
//            Role role = roles.get(0);
//            //得到仓库的ID，然后恢复库存
//            String warehouseID = this.getWarehouseID(order, buyer, role);
//
//            List<OrderContent> orderContents = order.getOrderContents();
//            // 入库
//            InStock inStock = new InStock();
//            inStock.setInStockID(Identities.uuid2());
//            inStock.setInStockType(InStockType.订单取消.getValue());
//            inStock.setInStocker(order.getBuyer());
//            inStock.setProofID(order.getOrderID());
//            inStock.setWarehouseID(warehouseID);
//            inStock.setModifyDate(modifyDate);
//            List<InOutStockDetail> inOutStockDetails = new ArrayList<>();
//            for (OrderContent orderContent : orderContents) {
//                buildInOutStockDetail(modifyDate, order, inOutStockDetails, orderContent);
//            }
//            inStock.setInOutStockDetails(inOutStockDetails);
//            iStockService.addInStock(inStock);
//            order.setStatus(OrderStatus.订单取消1109.getValue());
//        }
//    }
//
//    @Override
//    public ReturnBean<String> cancelOrder(String orderID, Integer orderStatus) {
//        return null;
//    }
//
//    private void buildInOutStockDetail(
//            Long modifyDate, Order order, List<InOutStockDetail> inOutStockDetails, OrderContent orderContent) {
//        CommodityTerminal commodityTerminal = getCommodityTerminal(String.valueOf(order.getOrderType()),
//                orderContent.getCommodityChannelID());
//        InOutStockDetail inOutStockDetail = new InOutStockDetail();
//        inOutStockDetail.setInOutStockDetailID(Identities.uuid2());
//        inOutStockDetail.setCommodityTerminalID(commodityTerminal.getCommodityTerminalID());
//        inOutStockDetail.setNum(orderContent.getNum());
//        inOutStockDetail.setModifyDate(modifyDate);
//        inOutStockDetails.add(inOutStockDetail);
//    }
//
//    @Override
//    public List<Order> findByPayTimeIsNullAndPayDeadlineLessThan(Long payDeadline) {
//        return saleOrderRepository.findByPayTimeIsNullAndPayDeadlineLessThan(payDeadline);
//    }
//
//    @Override
//    public List<Order> findByPlaceOrderTypeAndStatusAndOrderTypeNotAndPayDeadlineLessThan(
//            Integer placeOrderType, Integer status, Integer orderType, Long payDeadline) {
//        return saleOrderRepository.findByPlaceOrderTypeAndStatusAndOrderTypeNotAndPayDeadlineLessThan(placeOrderType,
//                status, orderType, payDeadline);
//    }
//
//    @Override
//    public ReturnBean<List<net.wofly.sale.order.domain.OrderType>> getAllOrderTypes() {
//        List<net.wofly.sale.order.domain.OrderType> orderTypes = iOrderTypeService.findByStatus(
//                CommonStatus.有效.getValue());
//        net.wofly.sale.order.domain.OrderType orderType = new net.wofly.sale.order.domain.OrderType();
//        orderType.setOrderTypeID("-1");
//        orderType.setOrderTypeName("所有订单");
//        orderTypes.add(orderType);
//        return new ReturnBean<>(ResultCode.SUCCESS, "获取订单类型成功", orderTypes);
//    }
//
//    @Override
//    public ReturnBean<List<net.wofly.sale.order.domain.OrderType>> getOrderTypeByRole(String roleID) throws
//            CloneNotSupportedException {
//        List<net.wofly.sale.order.domain.OrderType> orderTypesReturn = new ArrayList<>();
//        List<net.wofly.sale.order.domain.OrderType> orderTypes = iRoleOrderTypeService.findByRoleIDAndStatus(
//                roleID, CommonStatus.有效.getValue());
//
//        if (CollectionUtils.isNotEmpty(orderTypes)) {
//            //查找角色的默认订单类型
//            RoleDefaultOrderType roleDefaultOrderType = iRoleDefaultOrderTypeService.findByRoleID(roleID);
//            for (net.wofly.sale.order.domain.OrderType orderType : orderTypes) {
//                if (orderType.getOrderTypeID().equals(roleDefaultOrderType.getOrderType())) {
//                    orderType.setIsDefault(1);
//                }
//                //根据角色获取订单类型接口返回结果中去除还货订单，还货订单又单独的下单入口
//                if (!OrderType.还货订单.getValue().toString().equals(orderType.getOrderTypeID())) {
//                    net.wofly.sale.order.domain.OrderType orderTypeClone = orderType.clone();
//                    orderTypesReturn.add(orderTypeClone);
//                }
//            }
//        }
//        return new ReturnBean<>(ResultCode.SUCCESS, "根据角色获取订单类型成功", orderTypesReturn);
//    }
//
//    /**
//     * 获取订单状态，订单查询页面搜索条件
//     */
//    @Override
//    public ReturnBean<List<OrderStatusDto>> getOrderStatus() {
//        OrderStatus[] values = OrderStatus.values();
//        List<OrderStatusDto> orderStatuses = new ArrayList<>();
//
//        for (OrderStatus value : values) {
//            if (!value.getName().equals("订单取消")) {
//                OrderStatusDto dto = new OrderStatusDto(value.getValue(), value.getName());
//                orderStatuses.add(dto);
//            }
//        }
//        OrderStatusDto dto = new OrderStatusDto(9, "订单取消");
//        orderStatuses.add(dto);
//
//        return new ReturnBean<List<OrderStatusDto>>(ResultCode.SUCCESS, "获取订单状态成功", orderStatuses);
//    }
//
//    /**
//     * 更改订单类型
//     *
//     * @param orderType
//     * @param order
//     * @return
//     */
//    @Override
//    public ReturnBean<Order> changeOrderType(Integer orderType, Order order) throws CloneNotSupportedException {
//        order.setPlaceOrderType(PlaceOrderType.代客下单.getValue());
//        order.setOrderType(orderType);
//
//        for (OrderContent orderContent : order.getOrderContents()) {
//            if (orderContent.getCommodity() == null || org.apache.commons.lang3.StringUtils.isBlank(
//                    orderContent.getCommodity().getCommodityID())) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "商品ID不能为空！");
//            }
//            Commodity commodity = iCommodityService.findOne(orderContent.getCommodity().getCommodityID());
//            if (commodity == null) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE,
//                        "商品(" + orderContent.getCommodity().getCommodityID() + ")未找到！");
//            }
//
//            //查找订单类型和渠道的关系
//            OrderTypeChannelMapping orderTypeChannelMapping = iOrderTypeChannelMappingService.findByOrderType(
//                    String.valueOf(orderType));
//            if (null == orderTypeChannelMapping) {
//                logger.info(">>> 未找到订单类型和渠道的关系配置数据...");
//            }
//
//            //查找商品渠道
//            CommodityChannel commodityChannel = iCommodityChannelService.findByCommodityIDAndChannel(
//                    commodity.getCommodityID(), orderTypeChannelMapping.getChannel());
//            orderContent.getCommodity().setCommodityChannel(commodityChannel);
//
//            //orderContent.setCommodity(commodity);
//            orderContent.setCommodityChannelID(commodityChannel.getCommodityChannelID());
//        }
//
//        ReturnBean<Order> returnBean = this.handleOrder(order);
//        if (ResultCode.SUCCESS.intValue() == returnBean.getCode().intValue()) {
//            return new ReturnBean<>(ResultCode.SUCCESS, "更改订单类型成功", returnBean.getResult());
//        } else {
//            return new ReturnBean<>(returnBean.getCode(), returnBean.getMsg(), returnBean.getResult());
//        }
//    }
//
//    /**
//     * 重新写入订单的真正支付信息，向payInfo表插入记录
//     *
//     * @param orderID
//     * @return
//     */
//    @Override
//    public ReturnBean<String> reWritePayInfo4WorkFlowConfirmReceiveable(String orderID) {
//        Order order = findOne(orderID);
//        if (order == null) {
//            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "orderID不正确");
//        }
//        //生成支付信息
//        PayInfo payInfo = new PayInfo();
//        payInfo.setPayInfoID(Identities.uuid2());
//        payInfo.setOrderID(orderID);
//        //默认设置为订单的应付款金额
//        payInfo.setAmount(order.getRealPrice());
//        payInfo.setPayAccount(null);
//        payInfo.setPayTime(System.currentTimeMillis());
//        payInfo.setPayType(PayType.现金.getValue());
//        iPayInfoService.save(payInfo);
//
//        //更新订单的支付时间
//        order.setPayTime(System.currentTimeMillis());
//        save(order);
//
//        return new ReturnBean<>(ResultCode.SUCCESS, "重写订单支付信息成功");
//    }
//
//    /**
//     * 获取客户的还货商品库存
//     *
//     * @param customerUserID
//     * @return
//     */
//    @Override
//    public ReturnBean<List<ReturnGoodsDtoResp>> getCustomerReturnGoodsStock(
//            String customerUserID) {
//        List<Stock> stockList = iStockService.findByWarehouseIDAndNumGreaterThan(customerUserID, 0);
//        if (!CollectionUtils.isEmpty(stockList)) {
//            List<ReturnGoodsDtoResp> respList = new ArrayList<>();
//            for (Stock stock : stockList) {
//                Commodity commodity = iCommodityTmlService.findCommodityByCommodityTerminalID(
//                        stock.getCommodityTerminalID());
//                ReturnGoodsDtoResp respDto = new ReturnGoodsDtoResp();
//                respDto.setCommodityTmlID(stock.getCommodityTerminalID());
//                respDto.setRestNum(stock.getNum());
//                respDto.setCommodity(commodity);
//                respList.add(respDto);
//            }
//            return new ReturnBean<>(ResultCode.SUCCESS, "获取客户的还货商品库存成功", respList);
//        }
//        return new ReturnBean<>(ResultCode.SUCCESS, "获取客户的还货商品库存成功");
//    }
//
//    /**
//     * 创建订单（还货订单专用）
//     *
//     * @param returnGoodsDtoReq
//     * @return
//     */
//    @Override
//    public ReturnBean<Order> createOrderForReturnGoods(ReturnGoodsDtoReq returnGoodsDtoReq) {
//        Long modifyDate = System.currentTimeMillis();
//        //下单人
//        User buyer = iUserService.findOne(returnGoodsDtoReq.getBuyerID());
//        String orderID = Identities.uuid2();
//        Long modifyTime = System.currentTimeMillis();
//
//        List<Role> roles = iUserRoleService.findRolesByUserID(returnGoodsDtoReq.getCustomerUserID());
//        if (CollectionUtils.isEmpty(roles)) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "客户没有分配角色，请先给客户分配角色");
//        }
//        Integer channel = null;
//        if (roles.get(0).getRoleID().equals(RoleEnum.流通客户.getValue())) {
//            channel = Channel.流通.getValue();
//        } else if (roles.get(0).getRoleID().equals(RoleEnum.酒店客户.getValue())) {
//            channel = Channel.酒店.getValue();
//        }
//
//        List<ReceivingAddr> receivingAddrList = iReceivingAddrService
//                .findByUserIDAndStatusOrderByDefaultFlagDesc(
//                        returnGoodsDtoReq.getCustomerUserID(), CommonStatus.有效.getValue());
//        if (CollectionUtils.isEmpty(receivingAddrList)) {
//            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未查询到客户的默认收货地址信息，请先维护客户收货地址");
//        }
//        //选取客户的默认收货地址
//        OrderReceivingAddr addr = new OrderReceivingAddr();
//        addr.setOrderReceivingAddrID(Identities.uuid2());
//        addr.setOrderID(orderID);
//        addr.setReceivingAddrID(receivingAddrList.get(0).getReceivingAddrID());
//        addr.setModifyDate(modifyTime);
//        iOrderReceivingAddrService.save(addr);
//
//        Order order = new Order();
//        order.setOrderID(orderID);
//        order.setPlaceOrderType(PlaceOrderType.代客下单.getValue());
//        order.setBuyer(returnGoodsDtoReq.getBuyerID());
//        order.setCustomerUserID(returnGoodsDtoReq.getCustomerUserID());
//        order.setOrderType(OrderType.还货订单.getValue());
//        order.setStatus(OrderStatus.订单己支付.getValue());
//        order.setGoodTransportType(GoodTransportType.送货上门.getValue());
//
//        TakeGoodsShopInfo takeGoodsShopInfo = new TakeGoodsShopInfo();
//        takeGoodsShopInfo.setOrderID(orderID);
//        takeGoodsShopInfo.setTakeGoodsShopInfoID(Identities.uuid2());
//        //销售的所属门店
//        takeGoodsShopInfo.setShopOrgID(buyer.getOrganizationID());
//        takeGoodsShopInfo.setModifyDate(modifyTime);
//        iTakeGoodsShopInfoService.save(takeGoodsShopInfo);
//
//        List<OrderContent> orderContents = new ArrayList<>();
//        //销售出库
//        OutStock outStock1 = new OutStock();
//        outStock1.setOutStockType(OutStockType.订单出库.getValue());
//        outStock1.setProofID(orderID);
//        outStock1.setOutStocker(order.getBuyer());
//        outStock1.setModifyDate(modifyDate);
//
//        //客户出库
//        OutStock outStock2 = new OutStock();
//        outStock2.setOutStockType(OutStockType.订单出库.getValue());
//        outStock2.setProofID(orderID);
//        outStock2.setOutStocker(order.getBuyer());
//        outStock2.setModifyDate(modifyDate);
//
//        List<InOutStockDetail> inOutStockDetails = new ArrayList<>();
//        for (ReturnCommodityTmlDto tmlDto : returnGoodsDtoReq.getReturnCommodityTmlDtos()) {
//            Commodity commodity = iCommodityTmlService.findCommodityByCommodityTerminalID(
//                    tmlDto.getCommodityTmlID());
//            CommodityChannel commodityChannel = iCommodityChannelService.findByCommodityIDAndChannel(
//                    commodity.getCommodityID(), String.valueOf(channel));
//
//            //先查询销售的库存
//            Stock stock = iStockService.findByWarehouseIDAndCommodityTerminalID(buyer.getWarehouseID(),
//                    tmlDto.getCommodityTmlID());
//            if (null == stock) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未查询到业务员（销售）相对的商品库存信息，请检查");
//            }
//            if (stock.getNum() < tmlDto.getNum()) {
//                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "还货商品数量超过业务员（销售）的库存数据，请检查");
//            }
//            InOutStockDetail inOutStockDetail = new InOutStockDetail();
//            inOutStockDetail.setInOutStockDetailID(Identities.uuid2());
//            inOutStockDetail.setCommodityTerminalID(tmlDto.getCommodityTmlID());
//            inOutStockDetail.setNum(tmlDto.getNum());
//            inOutStockDetail.setModifyDate(modifyDate);
//            inOutStockDetails.add(inOutStockDetail);
//
//            OrderContent content = new OrderContent();
//            content.setOrderContentID(Identities.uuid2());
//            content.setOrderID(orderID);
//            content.setNum(tmlDto.getNum());
//            content.setPreorderNum(content.getNum());
//            content.setCommodityChannelID(commodityChannel.getCommodityChannelID());
//            content.setPrice(commodityChannel.getCommodityChannelPrise());
//            content.setTotalPrice(commodityChannel.getCommodityChannelPrise() * content.getNum());
//            content.setModifyDate(modifyTime);
//            orderContents.add(content);
//        }
//        order.setOrderContents(orderContents);
//
//        //生成订单编号
//        String orderNO = generateOrderNO();
//        order.setOrderNo(orderNO);
//
//        order = save(order);
//
//        outStock1.setInOutStockDetails(inOutStockDetails);
//        iStockService.addOutStock(outStock1);
//
//        outStock2.setInOutStockDetails(inOutStockDetails);
//        iStockService.addOutStock(outStock2);
//
//        return new ReturnBean<>(ResultCode.SUCCESS, "创建订单（还货订单专用）成功", order);
//    }
//
//    @Override
//    public List<Order> findToDoList(String userID) {
//        List<Order> orders = iOrderFlowService.findToDoList(userID);
//
//        if (CollectionUtils.isNotEmpty(orders)) {
//            for (Order order : orders) {
//                getOrderInfo(order);
//            }
//        }
//
//        return orders;
//    }
//
//    @Override
//    public ReturnBean<Order> getOrderForFlow(String orderID) {
//        Order order = this.findOne(orderID);
//
//        if (order == null) {
//            return new ReturnBean<>(611, "业务工作流实例不存在");
//        }
//
//        if (order.getTaskID() == null) {
//            return new ReturnBean<>(612, "业务工作流任务不存在");
//        }
//
//        getOrderInfo(order);
//
//        iOrderFlowService.getOrderForFlow(order);
//
//        return new ReturnBean<>(0, "获取工作流信息成功", order);
//    }
//
//    @Override
//    public ReturnBean<PageWrapper<Order>> getMyOrders(
//            String userID, String orderNo, Integer orderType, String customerName, Integer status, Integer pageNum,
//            Integer pageSize) {
//
//        //查到用户角色的得到是会员或者是员工
//        List<Role> rolesByUserID = iUserRoleService.findRolesByUserID(userID);
//        if (CollectionUtils.isEmpty(rolesByUserID)) {
//            return new ReturnBean<PageWrapper<Order>>(ResultCode.ERROR_SERVICE, "未找到对应的用户角色");
//        }
//
//        if (rolesByUserID.get(0).getRoleID().startsWith("1")) {
//            //员工
//            return this.getSalerOrder(userID, orderNo, orderType, customerName, status, pageNum, pageSize);
//        } else {
//            //客户
//            return this.getCustomerOrder(userID, pageNum, pageSize);
//        }
//    }
//
//    @Override
//    public List<Order> findByBuyerAndOrderCommitTimeBetween(String userID, Long startTime, Long endTime) {
//        return saleOrderRepository.findByBuyerAndOrderCommitTimeBetween(userID, startTime, endTime);
//    }
//
//    @Override
//    public List<Order> findByBuyerAndFinishedTimeBetween(String userID, Long startTime, Long endTime) {
//        return saleOrderRepository.findByBuyerAndFinishedTimeBetween(userID, startTime, endTime);
//    }
//
//    @Override
//    public List<Order> findByBuyerAndPayTimeBetween(String userID, Long startTime, Long endTime) {
//        return saleOrderRepository.findByBuyerAndPayTimeBetween(userID, startTime, endTime);
//    }
//
//    /**
//     * 检查订单是否有赠品（给工作流用，白条订单发货时，才进行减库存，如果有赠品，则继续调用减库存接口，反之则不调用）
//     *
//     * @param orderID
//     * @return
//     */
//    @Override
//    public boolean checkOrderHasGift(String orderID) {
//        return false;
//    }
//
//    /**
//     * 支付方式为白条订单的减库存（给工作流用）
//     *
//     * @param orderID
//     * @return
//     */
//    @Override
//    public ReturnBean<String> decreaseStockForBaiTiaoOrder(String orderID) {
//        return null;
//    }
}
